package com.tender.service.impl;

import com.alibaba.fastjson.JSON;
import com.tender.request.LoginRequest;
import com.tender.service.JwtLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tender.jwt.JwtTokenManager;
import com.tender.util.ShiroUtil;
import com.tender.domain.ShiroUser;
import com.tender.response.LoginResponse;


import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class JwtLoginServiceImpl implements JwtLoginService {

    @Autowired
    private JwtTokenManager jwtTokenManager;

    @Override
    public String jwtLogin(LoginRequest request) {
        LoginResponse baseResponse = new LoginResponse();

        Map<String, String> map = new HashMap<>();
        String jwtToken = null;
        UsernamePasswordToken token = new UsernamePasswordToken(request.getLoginName(), request.getPassWord());
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        String shiroSessionId = ShiroUtil.getShiroSessionId();
        // 登录后颁发的令牌
        ShiroUser shiroUser = ShiroUtil.getShiroUser();
        Map<String, Object> claims = new HashMap<>();
        claims.put("shiroUser", JSON.toJSONString(shiroUser));
        jwtToken = jwtTokenManager.issuingToken(request.getLoginName(), subject.getSession().getTimeout(), shiroSessionId, claims);
        map.put("jwtToken", jwtToken);

        log.info("====> jwtToken: {}", jwtToken);

        return jwtToken;
    }
}
